<?php

namespace Home\Controller;

use Think\Controller;
use Home\Mail\PHPMailer;
use Home\Controller\CaptchaController;
use Think\Crypt;

class FindpassController extends Controller {

    public function index() {
        $this->display();
    }

    public function email() {
        if (IS_AJAX) {
            $email = I("get.email");
            $userInfoModel = new \Home\Model\UserInfoModel();
            if (!$userInfoModel->check_email($email)) {
                $this->ajaxReturn(array('ret' => 7, 'msg' => '邮箱格式错误'), 'json');
            }
            session("[start]");

            $user_add_info = $userInfoModel->where("email='%s'", $email)->find();

            if ($email != $user_add_info['email']) {
                $this->ajaxReturn(array('ret' => 8, 'msg' => '邮箱输入错误'), 'json');
            }

            $_SESSION['email'] = $email;

            $captcha = I("get.captcha");
            $verify = new CaptchaController();
            if (!$verify->check_verify($captcha)) {
                $this->ajaxReturn(array('ret' => 5, 'msg' => '验证码错误'), 'json');
            }
            /**
             * 需要根据邮箱去用户中心获取用户数据。
             * 生成token保存到memcache 24小时
             */
            $userModel = new \Home\Model\UserModel();
            $userinfo = $userModel->where("uid='%d'", $user_add_info['uid'])->find();
            $token = md5($userinfo['uid'] . $userinfo['username'] . $email);
            $this->mem = memcache_connect('localhost', 11211);
            $uuid = uniqid($email, TRUE);
            $this->mem->set($uuid, $token, 0, 86400);

            $url = "http://www.248game.com/index.php?s=/findpass/uppass&token=" . $token . "&uuid=" . $uuid . "&username=" . $userinfo['username'];
            $subject = "678fu网页游戏 设置新密码确认信";
            $body = "<table width=80% border=0 cellspacing=0 cellpadding=5 style=font:normal 14px/24px Tahoma, '宋体';>";
            $body.="<tr><td>亲爱的{$userinfo['username']}:<br/></td></tr>";
            $body.="<tr><td><strong>您于" . date("Y-m-d H:i:s") . "在765G网页游戏 (www.765G.com) 使用了取回密码服务!</strong><br/></td></tr>";
            $body.="<tr><td><br/><hr size=1 noshade=noshade color=#dddddd /></td></tr>";
            $body.="<tr><td><a href='" . $url . "' target='_blank'>点我重置密码</a><br/><br/>";
            $body.="请勿直接回复该邮件，有关 678fu通行证 的更多帮助信息，请访问：<a href='http://www.248game.com' target='_blank'>www.248game.com</a></td>";
            $body.="</tr></table>";
            $flag = $this->send_mail($email, $subject, $body);
            //邮箱发送成功，则，初始化用户密码。
            $data['password'] = $token;
            $userModel->where("uid='%d'", $uid)->save($data);
            $this->ajaxReturn($flag, 'json');
        }
        $this->display();
    }

    private function send_mail($email, $subject, $body) {

        //include_once(APP_PATH.'Home/Mail/PHPMailer.class.php');      
        //var_dump(is_file(APP_PATH.'Home/Mail/phpmailer.class.php'));exit;
        //include_once(APP_PATH."Home/Mail/SMTP.class.php"); // optional, gets called from within class.phpmailer.php if not already loaded
        $mail = new PHPMailer; // the true param means it will throw exceptions on errors, which we need to catch
        $mail->IsSMTP(); // telling the class to use SMTP
        try {
            $mail->Host = "smtp.exmail.qq.com"; // SMTP server
            $mail->CharSet = "utf-8";
            $mail->SMTPDebug = 2;                     // enables SMTP debug information (for testing)
            $mail->SMTPAuth = true;                  // enable SMTP authentication
            $mail->Host = "smtp.exmail.qq.com"; // sets the SMTP server
            $mail->Port = 25;                    // set the SMTP port for the GMAIL server
            $mail->Username = "service@678fu.com"; // SMTP account username
            $mail->Password = "678fu@$^*)";        // SMTP account password
            $mail->AddReplyTo('service@678fu.com', '678fu');
            $mail->AddAddress($email, '678fu用户');
            $mail->SetFrom('service@678fu.com', '678fu');
            $mail->Subject = $subject;
            $mail->AltBody = 'text/html';
            $mail->MsgHTML($body);
            if (!$mail->Send()) {
                return array('ret' => '1', 'msg' => '邮件发送失败');
            } else {
                return array('ret' => '0', 'msg' => '邮件发送成功');
            }
        } catch (phpmailerException $e) {
            echo $e->errorMessage();
            exit();
            echo "11";
            exit();
        } catch (Exception $e) {
            echo "22";
            exit();
        }
    }

    /**
     * 字符串替换  steven@qq.com 替换成 ste***@qq.com
     * @param type $mail
     * @return type
     */
    private function replace_mask($mail) {
        $email = $mail;
        $val = strpos($email, '@') / 2;
        $replace = '';
        for ($i = 0; $i < $val; $i++) {
            $replace.='*';
        }
        $str = substr($email, $val, $val);
        $output = str_replace($str, $replace, $email);
        return $output;
    }

    public function sendsuccess() {
        session('[start]');
        $emial = $this->replace_mask($_SESSION['email']);
        $this->assign('mask_email', $emial);        
        $this->display();
    }

    public function uppass() {
        $uuid = I('get.uuid');
        $token = I('get.token');
        $username = I('get.username');
        $mem = memcache_connect('localhost', 11211);
        if (IS_AJAX) {
            $newpass = I('get.newpass');
            $renpass = I('get.renpass');
            $username = I('get.username');
            if ($newpass == '' || $renpass == '') {
                $this->ajaxReturn(array('ret' => 12, 'msg' => '密码不能为空！'), 'json');
            }
            if ($newpass != $renpass) {
                $this->ajaxReturn(array('ret' => 13, 'msg' => '两次密码输入不一至'), 'json');
            }
            $userModel = new \Home\Model\UserModel;
            $data['password'] = Crypt::Crypt_Hash_Create($newpass);

            if ($userModel->where("username='" . $username . "'")->save($data)) {
                $mem->delete($uuid);
                $this->ajaxReturn(array('ret' => 0, 'msg' => '密码修改成功'));
            } else {
                $this->ajaxReturn(array('ret' => 1, 'msg' => '密码修改失败'));
            }
        }
        $tmp = $mem->get($uuid);
        if ($tmp && ($tmp == $token)) {
            //修改密码页面
            $this->assign('username', $username);
            $this->assign('on3a', 'on3a');
            $this->display("");
        } else {
            $this->error("页面已经过期，如果需要重设密码，请重新申请！", U('findpass/index'));
        }
    }

}
